﻿using Autofac;
using Autofac.Core.Lifetime;
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Common.IOC
{
    public class AutofacContainer
    {
        /// <summary>
        /// Autofac容器
        /// </summary>
        public static ILifetimeScope Container { get; set; }

        /// <summary>
        /// 从IOC容器获取指定服务
        /// </summary>
        public static TService Resolve<TService>(bool lifeTimeScope = true)
        {
            try
            {
                if (lifeTimeScope)
                {
                    //通过上下文访问器获取Http上下文
                    var context = Container.Resolve<IHttpContextAccessor>().HttpContext;
                    //从请求服务里获取IOC容器
                    var scope = context.RequestServices.GetService(typeof(ILifetimeScope)) as ILifetimeScope;
                    //获取服务（生命周期范围为请求结束就结束）
                    return scope.Resolve<TService>();
                }
                else
                {
                    //标记该服务的生命周期为每次请求作用域
                    return Container.BeginLifetimeScope(MatchingScopeLifetimeTags.RequestLifetimeScopeTag).Resolve<TService>();
                }
            }
            catch
            {
                return Container.BeginLifetimeScope(MatchingScopeLifetimeTags.RequestLifetimeScopeTag).Resolve<TService>();
            }
        }
    }
}
